Access Modifiers

Access Modifiers in scala are used to define the access field of members of packages, classes or objects in scala.For using an access modifier, you must include its keyword in the definition of members of package, class or object.These modifiers will restrict accesses to the members to specific regions of code.

There are Three types of access modifiers available in Scala:
  • Private
  • Protected
  • Public
Private: When a member is declared as private, we can only use it inside defining class or through one of its objects.The private access modifier can be used for variables and methods as well.
class abc{
private var a:Int = 10
def show(){
println(a)
}
}
class xyz{
def show1(){
var b=20
println(b)
}
}

object Demo{
def main(args:Array[String]){
var p = new abc()
var p1 = new xyz()
p.a = 12
p.show()
p1.show1()
}
}

Here we declared a variable ‘a’ private and now it can be accessed only inside it’s defining class or through classes object.

Protected: They can be only accessible from sub classes of the base class in which the member has been defined.

    class abc{ 
         protected var a:Int = 10 
    } 
    class xyz extends abc{ 
        def display(){ 
            println("a = "+a) 
        } 
    } 
    object MainObject{ 
        def main(args:Array[String]){ 
            var s = new xyz() 
            s.display() 
        } 
    }  

Public: There is no public keyword in Scala. The default access level (when no modifier is specified) corresponds to Java’s public access level.We can access these anywhere.

class abc{
var a:Int = 10
def show(){
println(" a = "+a)
}
}

object Demo{
def main(args:Array[String]){
var a = new abc()
a.show()
}
}

No comments:

Post a Comment